package com.chenlonghai.sbmybatis.imgconfig;

import javax.servlet.MultipartConfigElement;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class WebAppConfig extends WebMvcConfigurerAdapter {
	   //获取配置文件中图片的路径 {
	 //获取配置文件中图片的路径
	@Value("${cbs.imagesPath}")
    private String mImagesPath;
	
	public static  String getImagesPath(){
		return new WebAppConfig().mImagesPath;
	}
	
	
	   @Override  
	    public void addCorsMappings(CorsRegistry registry) {  
	        registry.addMapping("/**")  
	                .allowedOrigins("*")  
	                .allowCredentials(true)  
	                .allowedMethods("GET", "POST", "DELETE", "PUT")  
	                .maxAge(3600);  
	    }
	

	//访问图片方法
	 @Override
	 public void addResourceHandlers(ResourceHandlerRegistry registry) {
	  if(mImagesPath.equals("") || mImagesPath.equals("${cbs.imagesPath}")){
	   String imagesPath = WebAppConfig.class.getClassLoader().getResource("").getPath();
	   if(imagesPath.indexOf(".jar")>0){
	    imagesPath = imagesPath.substring(0, imagesPath.indexOf(".jar"));
	   }else if(imagesPath.indexOf("classes")>0){
	    imagesPath = "file:"+imagesPath.substring(0, imagesPath.indexOf("classes"));
	   }
	   imagesPath = imagesPath.substring(0, imagesPath.lastIndexOf("/"))+"/images/";
	   mImagesPath = imagesPath;
	  }
	  LoggerFactory.getLogger(WebAppConfig.class).info("imagesPath="+mImagesPath);
	   registry.addResourceHandler("/images/**").addResourceLocations(mImagesPath);  
	   super.addResourceHandlers(registry);
	 }
	 
	 /**
	     * 在配置文件中配置的文件保存路径
	     */
	
	  @Value("${cbs.location}")
	    private String location;
	    @Bean
	    public MultipartConfigElement multipartConfigElement(){
	        MultipartConfigFactory factory = new MultipartConfigFactory();
	        //文件最大KB,MB
	        factory.setMaxFileSize("2MB");
	        //设置总上传数据总大小
	        factory.setMaxRequestSize("10MB");
	        return factory.createMultipartConfig();
	    }
}
